package com.umfwechat.h5.controller.oauch;

import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.umfwechat.common.code.RetCode;
import com.umfwechat.common.constant.CommonConsts;
import com.umfwechat.common.constant.ConfigConsts;
import com.umfwechat.common.constant.MsgConsts;
import com.umfwechat.common.constant.PropertyConsts;
import com.umfwechat.common.constant.ValueConsts;
import com.umfwechat.common.prop.UmfPropModel;
import com.umfwechat.util.HttpUtil;
import com.umfwechat.util.PropertyUtil;
import com.umfwechat.util.ReqMessageUtil;
import com.umfwechat.util.ResultJsonUtil;
import com.umfwechat.util.StringUtil;
import com.umfwechat.util.wx.WeixinUtil;
import com.umfwechat.wx.pojo.AccessTokenOAuth;
import com.umpay.operation.model.edrawInf.EdrawInf;
import com.umpay.operation.service.edrawInf.remote.EdrawInfServiceRemote;
import com.umpay.sp.model.common.ReqMessage;
import com.umpay.sp.model.common.ResMessage;
import com.umpay.sp.model.saas.AppChannel;
import com.umpay.sp.model.saas.StoreInf;
import com.umpay.sp.service.saas.remote.AppChannelServiceRemote;
import com.umpay.sp.service.saas.remote.StoreInfServiceRemote;
import com.umpay.sp.service.sys.remote.UserServiceRemote;
import com.umpay.sp.xml.XmlData;

@Controller
@RequestMapping("/h5/oAuchController")
public class OAuchController {
	
	private static Logger logger = LoggerFactory.getLogger(OAuchController.class);
	// 查询第三方用户、用户详情接口
	@Resource
	private UserServiceRemote userServiceRemote_sp;

	// 查询店铺部署详情列表接口
	@Resource
	private StoreInfServiceRemote storeInfServiceRemote;

	//渠道开通查询接口
	@Resource
	private AppChannelServiceRemote appChannelServiceRemote;

	// 查询银行账户信息的接口
	@Resource
	private EdrawInfServiceRemote edrawInfRemote;
	
	/**
	 * 获取用户的openid
	 */
	public String getopenId(HttpServletRequest request,HttpServletResponse response){
		Map<String, String[]> params = request.getParameterMap();
		String[] codes = params.get("code");
		String code = codes[0];//code 
		//获取用户的openid
		logger.info("获取用户的code+******************************"+code);	
		String openid = "";
		if(request.getSession().getAttribute("openid") != null){
			openid = request.getSession().getAttribute("openid").toString();
		}
		logger.info("从session中获取用户的openid+******************************"+openid);
		if(StringUtil.isEmpty(openid)){
			logger.info(" 获取网页授权access_token*************开始*********");
			
			String APPID2 = PropertyUtil.getProperties("umfWeChatPlat_appConf.properties").getProperty("saas.wx.appid");
			
			String APPSECRET2 = PropertyUtil.getProperties("umfWeChatPlat_appConf.properties").getProperty("saas.wx.appsecret");

			AccessTokenOAuth tokenOAuth = WeixinUtil.getAccessTokenOAuth(APPID2,APPSECRET2,code);
			logger.info(" 获取网页授权access_token*************结束*********");
			
			if(tokenOAuth!=null){
				logger.info("重新获取用户的penid"+tokenOAuth.getOpenid());
				openid = tokenOAuth.getOpenid();
				if(openid!=null||!"".equals(openid)){
					request.getSession().setAttribute("openid", openid);
				}
			}else{
				openid="";
			}
		}
		return openid;
	}
	
	/**
	 * 跳转到商户开通
	 * @throws Exception
	 */
	@RequestMapping(value = "/becomePartnery")
	public String becomePartnery(HttpServletRequest request,HttpServletResponse response) throws Exception {
		return "merchantOpen";
	}
	/**
	 * 跳转到产品介绍
	 * @throws Exception
	 */
	@RequestMapping(value = "/productIntroduce")
	public ModelAndView productIntroduce(HttpServletRequest request,HttpServletResponse response) throws Exception {
		return new ModelAndView("product");
	}
	
	/**
	 * 跳转到专属活动
	 * @throws Exception
	 */
	@RequestMapping(value = "/exclusiveActivity")
	public ModelAndView exclusiveActivity(HttpServletRequest request,HttpServletResponse response) throws Exception {
		
		return new ModelAndView("activity");
	}

	/**
	 * 跳转到常见问题
	 * @throws Exception
	 */
	@RequestMapping(value = "/commonProblem")
	public ModelAndView commonProblem(HttpServletRequest request,HttpServletResponse response) throws Exception {
		
		return new ModelAndView("commonProblem");
	}
	
	/**
	 * 跳转到成为代理
	 */
	@RequestMapping(value = "/becomeAgency")
	public ModelAndView becomeAgency(HttpServletRequest request,HttpServletResponse response) throws Exception {
		
		return new ModelAndView("cooperation");
	}
	
	/**
	 * 跳转到商户登录
	 * @throws Exception
	 */
	@RequestMapping(value = "/register")
	public String register(HttpServletRequest request,HttpServletResponse response) throws Exception {
		//获取openid
		String getopenId = this.getopenId(request, response);
		if(StringUtil.isEmpty(getopenId)){
			return "error";
		}
		return "merchantLogin";
	}
	
	/**
	 * 跳转到账单明细菜单
	 */
	@RequestMapping(value = "/billingDetail")
	public String billingDetail(HttpServletRequest request,HttpServletResponse response) throws Exception {
		//获取openid
		String getopenId = this.getopenId(request, response);
		//判断是否签约
		ResMessage resMessage = this.queryBefore(getopenId, request, response);
		logger.info("跳转到账单明细菜单resMessage       " + resMessage);
		if (resMessage.getRetCode().equals(RetCode.SUCCESS)) {
			// 判断是否签约
			String state = resMessage.getResMap().get("storeState").toString();
			if (state.equals("0")) { // 未签约，跳转首次签约页面
				return "index";
			}else if(state.equals("1")){                   //已签约，跳转账单明细
                request.getSession().setAttribute(CommonConsts.RANK,ValueConsts.PAYEE);
				return "choiceBill";
			}else if(state.equals("2")){
	            request.getSession().setAttribute(CommonConsts.RANK,ValueConsts.CASHIER);
				return "billMsg";
			}else{
				return "error";
			}
		}else{
			return "";
		}
	}
	
	
	/**
	 * 跳转到收款菜单
	 */
	@RequestMapping(value = "/gathering")
	public String gathering(HttpServletRequest request,HttpServletResponse response) throws Exception {
		// 获取openid
		String getopenId = this.getopenId(request, response);
		// 判断是否签约
		ResMessage resMessage = this.queryBefore(getopenId, request, response);
		logger.info("跳转到收款菜单resMessage       " + resMessage);
		if (resMessage.getRetCode().equals(RetCode.SUCCESS)) {
			// 判断是否签约
			String state = resMessage.getResMap().get("storeState").toString();
			if (state.equals("0")) { // 未签约，跳转首次签约页面
				return "index";
			} else if(state.equals("1")) { // 已签约，跳转收款
				return "gathering";
			}else if(state.equals("2")){
				return "gathering";
			}else{
				return "error";
			}
		} else {
			return "";
		}
	}
	
	/**
	 * 跳转到收银员管理菜单
	 */
	@RequestMapping(value = "/cashierManage")
	public ModelAndView cashierManage(HttpServletRequest request,HttpServletResponse response) throws Exception {
		// 获取openid
		String getopenId = this.getopenId(request, response);
		// 判断是否签约
		ResMessage resMessage = this.queryBefore(getopenId, request, response);
		logger.info("跳转到收银员管理菜单resMessage       " + resMessage);
		if (resMessage.getRetCode().equals(RetCode.SUCCESS)) {
			// 判断是否签约
			String state = resMessage.getResMap().get("storeState").toString();
			if (state.equals("0")) { // 未签约，跳转首次签约页面
				return new ModelAndView("index");
			} else if(state.equals("1")) { // 已签约，跳转收银员管理
				return new ModelAndView("choiceStore");
			}else if(state.equals("2")){
				return new ModelAndView("choiceStore");
			}else{
				return new ModelAndView("error");
			}
		} else {
			return new ModelAndView("");
		}
	}
	
	/**
	 * 跳转到店铺管理
	 */
	@RequestMapping(value = "/storeManage")
	public ModelAndView storeManage(HttpServletRequest request,HttpServletResponse response) throws Exception {
		// 获取openid
		String getopenId = this.getopenId(request, response);
		// 判断是否签约
		ResMessage resMessage = this.queryBefore(getopenId, request, response);
		logger.info("跳转到店铺管理resMessage       " + resMessage);
		if (resMessage.getRetCode().equals(RetCode.SUCCESS)) {
			// 判断是否签约
			String state = resMessage.getResMap().get("storeState").toString();
			logger.info("state    "+state);
			if (state.equals("0")) { // 未签约，跳转首次签约页面
				return new ModelAndView("index");
			} else if (state.equals("1")){ // 已签约，跳转收银员管理
				return new ModelAndView("storeMsg");
			}else if(state.equals("2")){                             //收银员
				return new ModelAndView("storeMsg");
			}else{
				return new ModelAndView("error");
			}
		} else {
			return new ModelAndView("");
		}
	}
	
	
	/**
	 * 判断产品签约状态
	 * @param request
	 * @param response
	 * @return result
	 */
	public ResMessage queryBefore(String openId,HttpServletRequest request,HttpServletResponse response) {
		logger.info("===判断产品签约状态接口===");
		// 获取openid失败
		if (openId == null || "".equals(openId)) {
			ResMessage resMessage = new ResMessage();
			resMessage.setRetCode(RetCode.FAIL);
			resMessage.setRetMsg("获取openId失败！");
			logger.info("获取openId失败");
			return resMessage;
		}
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			// ~~~~~~~~~~~~~~~~~~~根据openId查询userId（查询第三方用户接口）~~~~~~~~~~~~~~~~~~~~~~~
			logger.info("查询第三方用户接口openId：" + openId);
			ReqMessage reqMessage = ReqMessageUtil.makeSpReq();
			reqMessage.put("externaluserId", openId);
			logger.info("查询第三方用户接口入参：" + reqMessage);
			ResMessage resMessage = userServiceRemote_sp.queryUserBind(reqMessage);
			logger.info("查询第三方用户接口出参：" + resMessage);
			if (!resMessage.getRetCode().equals(RetCode.SUCCESS)) { // 查询错误
				if(resMessage.getRetCode().equals(RetCode.NO_DATA)){
					ResMessage ress = new ResMessage();
					ress.setRetCode(RetCode.SUCCESS);
					ress.setRetMsg("查询用户详情接口：无此用户！");
					Map<String, Object> resMapp = new HashMap<String, Object>();
					resMapp.put("storeState","3");	//标记此无此用户
					ress.setResMap(resMapp);
					return ress;
				}
				resMessage.setRetCode(RetCode.FAIL);
				resMessage.setRetMsg("查询第三方网站用户失败！");
				logger.info("查询第三方网站用户接口 ：数据库错误");
				return resMessage;
			}
			if (resMessage.getResMap().get("userId") == null) { // 未取到用户编号
				resMessage.setRetCode(RetCode.FAIL);
				resMessage.setRetMsg("未获取到用户编号");
				logger.info("查询第三方网站用户接口 ：未获取到用户编号");
				return resMessage;
			}
			String userId = resMessage.getResMap().get("userId").toString();
			//将用户编号放到session中
			request.getSession().setAttribute("userId", userId);

			//~~~~~~~~~~~~~~~~~~~~~~根据userId查询merId（主商户）（用户详情接口）~~~~~~~~~~~~~~~~~~~~~
			logger.info("调用查询用户详情接口");
			ReqMessage reqMess = ReqMessageUtil.makeSpReq();
			reqMess.getReqMap().put("userId", userId);
			logger.info("查询用户详情接口入参：" + reqMess);
			ResMessage resMess = userServiceRemote_sp.getUserByIdSaaS(reqMess);
			logger.info("查询用户详情接口出参：" + resMess);
			if (!resMess.getRetCode().equals(RetCode.SUCCESS)) { // 查询错误
				resMess.setRetCode(RetCode.FAIL);
				resMess.setRetMsg("查询用户详情失败！");
				logger.info("查询用户详情接口：未获取到主商户号");
				return resMess;
			}
			Map<String,Object> map = (Map<String, Object>) resMess.getResMap().get("merUser");
			//判断角色收银员
			Map userMap = (Map)resMess.getValue(XmlData.MER_USER);
			String merId = userMap.get("merId").toString(); //媒介标识
			merId = StringUtil.trim(merId);
			Integer rank = Integer.parseInt(userMap.get("rank").toString()); //身份
			if(rank == 1){
				ResMessage ress = new ResMessage();
				ress.setRetCode(RetCode.SUCCESS);
				ress.setRetMsg("查询用户详情接口成功！为收银员角色");
				Map<String, Object> resMapp = new HashMap<String, Object>();
				resMapp.put("storeState", "2");  //标记角色为收银员
				ress.setResMap(resMapp);
				return ress;
			}
			if (merId == null || merId.equals("")) { // 未取到用户编号
				resMess.setRetCode(RetCode.FAIL);
				resMess.setRetMsg("未获取到主商户号");
				logger.info("查询第三方网站用户接口 ：未获取到主商户号");
				return resMess;
			}
			//将主商户号放到session中
			request.getSession().setAttribute("merId", merId);
			// ~~~~~~~~~~~~~~~~~~~~~~根据主商户merId查询店铺列表 （ 店铺部署详情列表接口）~~~~~~~~~~~~~~~~~~~~~~
			logger.info("调用查询店铺部署详情列表接口");
			ReqMessage req = ReqMessageUtil.makeSpReq();
			req.getReqMap().put("merId", merId);
			req.getReqMap().put("registerProcsStates","'05','06','07','08','09','10'");
			logger.info("店铺部署详情列表接口入参" + req);
			ResMessage res = storeInfServiceRemote.getStoreInfList(req);
			logger.info("店铺部署详情列表接口出参" + res);
			if (!res.getRetCode().equals(RetCode.SUCCESS)) { // 查询错误
				res.setRetCode(RetCode.FAIL);
				res.setRetMsg("查询店铺列表失败");
				logger.info("查询店铺部署详情列表接口：未获取到店铺");
				return res;
			}
			List<StoreInf> storeInfList = (List<StoreInf>) res.getResMap().get("storeInfList");
			String totalSize = res.getResMap().get("totalSize").toString();
			if (totalSize == null || totalSize.equals("") || totalSize.equals("0")) { // 未取到店铺
				res.setRetCode(RetCode.FAIL);
				res.setRetMsg("用户未开通店铺");
				logger.info("店铺部署详情列表接口 ：结果不存在");
				return res;
			}
			// 遍历主商户下的店铺列表 获得店铺编号 调用渠道开通查询接口 依次判断店铺签约状态
			if(storeInfList == null || storeInfList.equals("") ){
				res.setRetCode(RetCode.FAIL);
				res.setRetMsg("用户未开通店铺");
				logger.info("店铺部署详情列表接口 ：结果不存在");
				return res;
			}
			for (int i = 0; i < storeInfList.size(); i++) {
				String storeId = storeInfList.get(i).getStoreId();   //取得店铺编号
				
				String productId_add = UmfPropModel.INSTANCE.getPropValue(ConfigConsts.PRODUCTID_IMPAY_ADDED);
				String productId = UmfPropModel.INSTANCE.getPropValue(ConfigConsts.PRODUCTID_IMPAY);
				//~~~~~~~~~~~~~~~~~~~~~~渠道开通查询接口，查询店铺产品签约状态~~~~~~~~~~~~~~~~~~~~~~
				ReqMessage reqq = ReqMessageUtil.makeSpReq();	
				Map<String, String> reqM = new HashMap<String, String>();
				reqM.put("appSysId", storeId);
				//reqM.put("mainProductId", PropertyUtil.getProperties("umfWeChatPlat_appConf.properties").getProperty("mainProductId"));	//立马付大产品号
				reqM.put("productIds","'"+productId+"','"+productId_add+"'");
				reqq.setReqMap(reqM);
				logger.info("调用查询渠道开通接口");
				logger.info("查询渠道开通接口入参：" + reqq);
				ResMessage ress =appChannelServiceRemote.getAppChannelListByProductids(reqq);
				logger.info("查询渠道开通接口出参：" + ress);
				if(!ress.getRetCode().equals(RetCode.SUCCESS)){		//查询失败
					ress.setRetCode(RetCode.FAIL);
					ress.setRetMsg("查询渠道开通接口失败");
					logger.info("查询渠道开通接口：未获取到商铺对应产品");
					return ress;
				}
				List<AppChannel> resultList = (List<AppChannel>) ress.getResMap().get("appChannelList");
				if(null==resultList||resultList.isEmpty()){
					continue;
				}
				if (resultList.get(0).getState().equals(4)) { // 未签约
					ress.setRetCode(RetCode.SUCCESS);
					ress.getResMap().put("storeId", storeId);
					ress.getResMap().put("storeState","0");	//标记此店铺未签约
					return ress;
				}
			}
			ResMessage ress = new ResMessage();
			ress.setRetCode(RetCode.SUCCESS);
			ress.setRetMsg("查询渠道开通接口成功，均已签约");
			Map<String, Object> resMapp = new HashMap<String, Object>();
			resMapp.put("merId", merId);
			resMapp.put("storeState", "1");  //标记店铺已签约
			ress.setResMap(resMapp);
			return ress;
		} catch (SQLException e) {
			logger.info("判断店铺签约失败:数据库错误！");
			resultMap.put("retCode", RetCode.FAIL);
			resultMap.put("retMsg", "判断店铺签约失败");
		} catch (Exception e) {
			logger.info("判断店铺签约失败", e);
			resultMap.put("retCode", RetCode.FAIL);
			resultMap.put("retMsg", "判断店铺签约失败");
		}
		ResMessage ress = new ResMessage();
		ress.setRetCode(RetCode.FAIL);
		ress.setRetMsg("查询渠道开通接口失败");
		Map<String, Object> resMap = new HashMap<String, Object>();
		resMap.put("openId", openId);
		ress.setResMap(resMap);
		return ress;
	}
	
	
	/**
	 * 判断商户是否绑定银行卡
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/settlementQueryCard")
	public String queryCard(HttpServletRequest request,HttpServletResponse response) {
		//获取openId
		String getopenId = this.getopenId(request, response);
		
		ResMessage queryBefore = this.queryBefore(getopenId,request, response);
		if (queryBefore.getRetCode().equals(RetCode.SUCCESS)) {
			// 判断是否签约
			String state = queryBefore.getResMap().get("storeState").toString();
			if (state.equals("0")) { // 未签约，跳转首次签约页面
				return "index";
			} else if(state.equals(ValueConsts.STATE_TWO)){
				return "error";
			}
			 	//已签约，判断绑卡状态
				logger.info("判断商户是否绑卡接口！");
				//从session中获取主商户号
				String merId = StringUtil.trim(request.getSession().getAttribute("merId").toString());
				logger.info("session中获取merId:" + merId);
				if(!merId.equals("") && merId != null ){
					// 调用查询绑定银行卡信息接口
					logger.info("查询商户绑定银行卡接口：merId"+merId);
					com.umpay.operation.common.ReqMessage req = ReqMessageUtil.makeOpReq();
				    Map<String, Object> reqMap = new HashMap<String, Object>();	
				    reqMap.put("merId", merId);
				    reqMap.put("delayDays", 1);
				    reqMap.put("state", "2");
//				    reqMap.put("recvBankAccPro", "0");//对公对私
				    req.setReqMap(reqMap);
					com.umpay.operation.common.ResMessage ress;
					try {
						logger.info("查询商户绑定银行卡入参："+req);
						ress = edrawInfRemote.queryEdrewInf(req);
						logger.info("查询商户绑定银行卡出参："+ress);
					} catch (Exception e){
						logger.info("查询商户绑定银行卡信息接口exception");
						return "error";
					}	
					if(ress == null || !ress.getRetCode().equals(RetCode.SUCCESS)){   //查询失败
						logger.info("查询商户绑定银行卡信息接口失败");
						return "error";
					}
					EdrawInf edrawInfReData =(EdrawInf) ress.getResMap().get("edrawInf");
					logger.info("edrawInfReData================="+edrawInfReData);
					//判断是否有绑卡信息
					if(edrawInfReData !=null ){	//已经绑卡
						logger.info("判断绑卡成功商户已绑卡merId："+merId + "进入settleChoiceStore");
//						return "settleChoiceStore";//2期
						return "incomeSettlement"; //3期
					}else{	 //未绑卡
						logger.info("判断绑卡成功商户未绑卡merId："+merId + "进入addBankCard");
						return "addBankCard";
					}
				}
				logger.info("merId获取失败！");
				return "error";
		} else {
			logger.info("判断签约失败！");
			return "error";
		}

	}
	
	

	public Map<String,Object> commonAccountQuery(String merId) {
		
		Map<String,Object> map=new HashMap<String, Object>();
		//通过主商户获取店铺信息
		ReqMessage reqM = ReqMessageUtil.makeSpReq();
		reqM.getReqMap().put("merId",merId);
		logger.info("店铺部署详情列表接口开始：req=" + reqM);
		ResMessage resM = storeInfServiceRemote.getStoreInfList(reqM);
		logger.info("店铺部署详情列表接口结束 ：res=" + resM);
		if(!RetCode.SUCCESS.equals(resM.getRetCode())){
			logger.info("店铺部署详情列表接口失败 ");
			map.put(CommonConsts.RETCODE,RetCode.FAIL);
			return map;
		}else if(ValueConsts.FLAG_ZERO.equals(resM.getValue(CommonConsts.TOTAL_SIZE).toString())){
			logger.info("店铺部署详情列表获取数据失败 ");
			map.put(CommonConsts.RETCODE,RetCode.FAIL);
			return map;
		}
		@SuppressWarnings("unchecked")
		List<StoreInf> listt = (List<StoreInf>)resM.getValue(CommonConsts.STOREINF_LIST);
		for (StoreInf storeInf : listt) {
			String storeType = storeInf.getStoreType();
			if(ValueConsts.STATE_ZERO.equals(storeType)){
				logger.info("店铺部署详情列表中有小微商户");
				map.put(CommonConsts.RETCODE,RetCode.SUCCESS);
				map.put(CommonConsts.ACCOUNTTYPE,ValueConsts.STATE_TWO);//有小微商户
			    return map;
			}
		}
		

		// 调用查询绑定银行卡信息接口
		logger.info("【调用查询商户绑定银行卡接口】merId：" + merId);
		com.umpay.operation.common.ReqMessage req = ReqMessageUtil.makeOpReq();
		Map<String, Object> reqMap = new HashMap<String, Object>();
		reqMap.put(CommonConsts.MERID, merId);
		reqMap.put(CommonConsts.DELAYDAYS, ValueConsts.EDRAW_DELAYDAYS);
		reqMap.put(CommonConsts.STATE, ValueConsts.EDRAW_STATE);
		//reqMap.put(CommonConsts.RECVBANKACCPRO,ValueConsts.EDRAW_RECVBANKACCPRO);
		req.setReqMap(reqMap);
		com.umpay.operation.common.ResMessage resq = null;
		try {
			logger.info("【查询商户绑定银行卡信息接口】输入参数：ReqMessage=" + req);
			resq = edrawInfRemote.queryEdrewInf(req);
			logger.info("【查询商户绑定银行卡信息接口】输出参数：ResMessage" + resq);
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("【查询商户绑定银行卡信息接口异常】");
			map.put(CommonConsts.RETCODE,RetCode.FAIL);
			return map;
		}

		if (!RetCode.SUCCESS.equals(resq.getRetCode())) { // 查询失败
			logger.info("【调用查询商户绑卡信息接口失败!】");
			map.put(CommonConsts.RETCODE,RetCode.FAIL);
			return map;
		}
		EdrawInf edrawInfReData = (EdrawInf) resq.getResMap().get(CommonConsts.EDRAWINF);
		if (edrawInfReData == null) { // 查询无数据
			logger.info("【调用查询商户绑卡信息接口无数据-需绑卡】merId：" + merId);
			map.put(CommonConsts.RETCODE,RetCode.SUCCESS);
			map.put(CommonConsts.ACCOUNTTYPE,ValueConsts.STATE_THREE);//未绑卡
			return map;
		}
		logger.info("判断此"+merId+"用户是对公还是对私账户");
		Short recvBankAccPro = edrawInfReData.getRecvBankAccPro();
		logger.info("此"+merId+"商户类型0对私1对公:" + recvBankAccPro);
		if(1 == recvBankAccPro){
			logger.info("商户类型为对公账户");
			map.put(CommonConsts.RETCODE,RetCode.SUCCESS);
			map.put(CommonConsts.ACCOUNTTYPE,ValueConsts.STATE_TWO);//对公账户
			return map;
		}
		
		//基金企业/个人开户信息查询接口路劲
		String fundOpenAccSearch = UmfPropModel.INSTANCE.getPropValue(ConfigConsts.FUNDOPENACCSEARCH);
		
		if (StringUtil.isEmpty(fundOpenAccSearch)) {
			logger.info("【获取基金企业/个人开户信息查询接口路劲失败】");
			map.put(CommonConsts.RETCODE,RetCode.FAIL);
			return map;
		}
		//基金编号
		String fundNo = UmfPropModel.INSTANCE.getPropValue(ConfigConsts.FUNDNO);
		//基金公司商户号
		String fundMerId = UmfPropModel.INSTANCE.getPropValue(ConfigConsts.FUNDMERID);
		if (StringUtil.isEmpty(fundNo)) {
			logger.info("【获取基金编码失败】");
			map.put(CommonConsts.RETCODE,RetCode.FAIL);
			return map;
		}
		if (StringUtil.isEmpty(fundMerId)) {
			logger.info("【获取基金渠道编码失败】");
			map.put(CommonConsts.RETCODE,RetCode.FAIL);
			return map;
		}
		
		Map<String, Object> params = new HashMap<String, Object>();
		//输入参数
		com.umfwechat.common.ReqMessage makeFundReq = ReqMessageUtil.makeFundReq();
		params.put(CommonConsts.RPID, makeFundReq.getRpid());//流水号
		params.put(CommonConsts.REQDATE, makeFundReq.getReqDate());//日期
		params.put(CommonConsts.REQTIME, makeFundReq.getReqTime());//时间
		params.put(CommonConsts.FUNDNO,fundNo);
		params.put(CommonConsts.FUNDMERID,fundMerId);
		params.put(CommonConsts.USERMERID,merId);
		params.put(CommonConsts.MERUSERID,merId);
		params.put(CommonConsts.BPRODUCTID,PropertyConsts.BPRODUCTID);
		Map<String, Object> res=null;
		try {
			logger.info("【基金企业/个人开户信息查询】httpPostForm2Xml请求数据：params"+params+ "访问路径url="+ fundOpenAccSearch);	
			res = HttpUtil.httpPostXStream2XStream(fundOpenAccSearch,params,"utf-8");
			logger.info("【基金企业/个人开户信息查询】httpPostForm2Xml返回结果="+res);
			if(!RetCode.SUCCESS.equals(StringUtil.trim(res.get(CommonConsts.RETCODE)))) { // 查询失败
				logger.info("【基金企业/个人开户信息查询未开户!】");
				map.put(CommonConsts.RETCODE,RetCode.SUCCESS);
				map.put(CommonConsts.ACCOUNTTYPE,ValueConsts.STATE_ONE);//未开户
				return map;
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("【基金企业/个人开户信息查询异常】"+e);
			map.put(CommonConsts.RETCODE,RetCode.FAIL);
			return map;
		}
		logger.info("【基金企业/个人开户信息查询已开户!】");
		map.put(CommonConsts.RETCODE,RetCode.SUCCESS);
		map.put(CommonConsts.ACCOUNTTYPE,ValueConsts.STATE_ZERO);//已开户
		return map;
	}
	
	/**
	 * 聚财通菜单
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/accumulateThrough",produces="application/json;charset=UTF-8")
	public String accumulateThrough(HttpServletRequest request,HttpServletResponse response) {
		
		//获取openId
		String getopenId = this.getopenId(request, response);
		//判断签约
		ResMessage queryBefore = this.queryBefore(getopenId,request, response);
		if (!RetCode.SUCCESS.equals(queryBefore.getRetCode())) {
		   return "error";
		}
		String merId = StringUtil.trim(request.getSession().getAttribute(CommonConsts.MERID));
		//TODO
        //merId="69000070";
		if(StringUtil.isEmpty(merId)){
			logger.info("获取merId为空"+merId);
			return "error";
		}
		
		String whiteList_merId = UmfPropModel.INSTANCE.getPropValue(ConfigConsts.WHITELIST_MERID);//基金白名单
		String fundPermission = UmfPropModel.INSTANCE.getPropValue(ConfigConsts.FUNDPERMISSION);//基金权限
		String[] split = whiteList_merId.split(CommonConsts.AND);
		List<String> list=Arrays.asList(split);
		if(ValueConsts.FLAG_ONE.equals(fundPermission)|| list.contains(merId)){
			String state = StringUtil.trim(queryBefore.getResMap().get(CommonConsts.STORESTATE));
			if (ValueConsts.STATE_ZERO.equals(state)) { // 未签约，跳转首次签约页面
				logger.info("此"+merId+"未签约，跳转首次签约页面");
				return "index";
			} else if(ValueConsts.STATE_TWO.equals(state) || ValueConsts.STATE_THREE.equals(state)){//收银员、无此用户
				logger.info("此"+merId+"收银员，无此权限；或无此用户");
				return "error";
			}

			Map<String, Object> commonAccountQuery = this.commonAccountQuery(merId);
			if (!RetCode.SUCCESS.equals(commonAccountQuery.get(CommonConsts.RETCODE))) {
				return "error";
			}
			if(ValueConsts.STATE_ONE.equals(commonAccountQuery.get(CommonConsts.ACCOUNTTYPE))){
				logger.info("此"+merId+"跳转未开户主页面");
				return "fundNotOpen"; //TODO 未开户
			}else if(ValueConsts.STATE_ZERO.equals(commonAccountQuery.get(CommonConsts.ACCOUNTTYPE))){
				logger.info("此"+merId+"跳转已开户主页面");
				return "fundOpenAccount";//TODO 已开户
			}else if(ValueConsts.STATE_THREE.equals(commonAccountQuery.get(CommonConsts.ACCOUNTTYPE))){
				logger.info("此"+merId+"用户未绑卡-去绑卡页面");
				return "addBankCardFund";
			}else{
				logger.info("此"+merId+"有小微商户，不能开户了");
				return "error";//有小微商户、或对公
			}
		}else{
			logger.info("此用户"+merId+"无权限");
			return "error";//无权限
		}
	}
	
	
	/**
	 * 是否开户、持仓份额
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/accountQuery",produces="application/json;charset=UTF-8")
	@ResponseBody
	public String accountQuery(HttpServletRequest request,HttpServletResponse response) {
		Map<String, Object> result = new HashMap<String, Object>();
		
		String rank = StringUtil.trim(request.getSession().getAttribute(CommonConsts.RANK));
        if(ValueConsts.CASHIER.equals(rank)){
        	logger.info("【收银员无此权限】");
    		result.put(CommonConsts.ACCOUNTTYPE,ValueConsts.STATE_TWO);//有收银员不显示
    		return ResultJsonUtil.resultJson(RetCode.SUCCESS,CommonConsts.SPACE,result);
        }
        String merId = StringUtil.trim(request.getSession().getAttribute(CommonConsts.MERID));
        
        //merId="68000165";//TODO
		if(StringUtil.isEmpty(merId)){
			logger.info("获取merId为空"+merId);
			return ResultJsonUtil.resultJson(RetCode.FAIL,CommonConsts.SPACE);
		}
		
		String whiteList_merId = UmfPropModel.INSTANCE.getPropValue(ConfigConsts.WHITELIST_MERID);//基金白名单
		String fundPermission = UmfPropModel.INSTANCE.getPropValue(ConfigConsts.FUNDPERMISSION);//基金权限
		String[] split = whiteList_merId.split(CommonConsts.AND);
		List<String> list=Arrays.asList(split);
		if(ValueConsts.FLAG_ONE.equals(fundPermission)|| list.contains(merId)){
			Map<String, Object> commonAccountQuery = this.commonAccountQuery(merId);
			if (!RetCode.SUCCESS.equals(commonAccountQuery.get(CommonConsts.RETCODE))) {
				return ResultJsonUtil.resultJson(RetCode.FAIL,CommonConsts.SPACE);
			}
			if(ValueConsts.STATE_ONE.equals(commonAccountQuery.get(CommonConsts.ACCOUNTTYPE))){
				logger.info("此"+merId+"用户未开基金账号");
				result.put(CommonConsts.ACCOUNTTYPE,ValueConsts.STATE_ONE);//未开户
	    		return ResultJsonUtil.resultJson(RetCode.SUCCESS,CommonConsts.SPACE,result);
			}else if(ValueConsts.STATE_TWO.equals(commonAccountQuery.get(CommonConsts.ACCOUNTTYPE))){
				logger.info("此"+merId+"用户有小微商户，不能再开基金账户");
				result.put(CommonConsts.ACCOUNTTYPE,ValueConsts.STATE_TWO);//有小微商户不显示
	    		return ResultJsonUtil.resultJson(RetCode.SUCCESS,CommonConsts.SPACE,result);
			}else if(ValueConsts.STATE_THREE.equals(commonAccountQuery.get(CommonConsts.ACCOUNTTYPE))){
				logger.info("此"+merId+"用户没绑卡-需绑卡");
				result.put(CommonConsts.ACCOUNTTYPE,ValueConsts.STATE_ZERO);//此用户没绑卡-需绑卡
	    		return ResultJsonUtil.resultJson(RetCode.SUCCESS,CommonConsts.SPACE,result);
			}
			
			
			String serviceUrl_esoopay = UmfPropModel.INSTANCE.getPropValue(ConfigConsts.SERVICEURL_ESOOPAY);
			if (StringUtil.isEmpty(serviceUrl_esoopay)) {
				logger.info("【获取esoopay-ip端口失败】");
				return ResultJsonUtil.resultJson(RetCode.FAIL, MsgConsts.E00433044);
			}
			String esoopay_J06001 = UmfPropModel.INSTANCE.getPropValue(ConfigConsts.ESOOPAY_J06001);
			if (StringUtil.isEmpty(esoopay_J06001)) {
				logger.info("【获取查询基金累积收益接口路径失败】");
				return ResultJsonUtil.resultJson(RetCode.FAIL, MsgConsts.E00433044);
			}
			
			//merId="7000998";//TODO
			//基金累积收益（业务线）/esoopay/J06001
			Map<String, Object> paramMap = new HashMap<String, Object>();
	        com.umfwechat.common.ReqMessage makeFundReq = ReqMessageUtil.makeFundReq();
			paramMap.put(CommonConsts.RPID, makeFundReq.getRpid());//流水号
			paramMap.put(CommonConsts.REQDATE, makeFundReq.getReqDate());//日期
			paramMap.put(CommonConsts.REQTIME, makeFundReq.getReqTime());//时间
			paramMap.put(CommonConsts.VERSION,ValueConsts.VERSION);//版本号
			paramMap.put(CommonConsts.MERID, PropertyConsts.FUNDMERID);//基金渠道编码
			paramMap.put(CommonConsts.USERMERID, merId);//用户所属的商户号
			paramMap.put(CommonConsts.USERID, merId);//用户编号
			paramMap.put(CommonConsts.FUNDNO, PropertyConsts.FUNDNO);//基金编号
			paramMap.put(CommonConsts.BPRODUCTID, PropertyConsts.BPRODUCTID);//基金业务产品号
			Map<String, Object> balanceMap;
			try {
				logger.info("【基金累积收益（业务线）】访问路径："+ serviceUrl_esoopay+esoopay_J06001 + " 输入参数：" + paramMap);	
				balanceMap = HttpUtil.httpPostForm2Xml(serviceUrl_esoopay+esoopay_J06001, paramMap);
				logger.info("【基金累积收益（业务线）】输出参数："+balanceMap);
				if(!RetCode.SUCCESS.equals(balanceMap.get(CommonConsts.RETCODE))){
					logger.info("【基金累积收益（业务线）】查询失败");
					return ResultJsonUtil.resultJson(RetCode.FAIL,CommonConsts.SPACE);
				}
			}catch (Exception e) {
				e.printStackTrace();
				logger.error(String.format("【基金累积收益（业务线）查询异常】"+e));
				return ResultJsonUtil.resultJson(RetCode.FAIL,CommonConsts.SPACE);
			}
			//持仓份额(元)
			String balance = StringUtil.trim(balanceMap.get(CommonConsts.BALANCE));
			logger.info("此"+merId+"基金份额balance="+balance);
			if(StringUtil.isEmpty(balance)){
				logger.info("此"+merId+"用户持仓份额为0");
				result.put(CommonConsts.ACCOUNTTYPE,ValueConsts.STATE_THREE);//持仓份额为0
	    		return ResultJsonUtil.resultJson(RetCode.SUCCESS,CommonConsts.SPACE,result);
			}else{
				if(ValueConsts.ZERO.equals(balance)){
					logger.info("此"+merId+"用户持仓份额为0");
					result.put(CommonConsts.ACCOUNTTYPE,ValueConsts.STATE_THREE);//持仓份额为0
		    		return ResultJsonUtil.resultJson(RetCode.SUCCESS,CommonConsts.SPACE,result);
				}
				logger.info("此"+merId+"用户持仓份额不为0");
				result.put(CommonConsts.ACCOUNTTYPE,ValueConsts.STATE_FOUR);//持仓份额不为0
	    		return ResultJsonUtil.resultJson(RetCode.SUCCESS,CommonConsts.SPACE,result);
			}
			
		}else{
			logger.info("此"+merId+"用户无权限");
			result.put(CommonConsts.ACCOUNTTYPE,ValueConsts.STATE_TWO);//无权限
    		return ResultJsonUtil.resultJson(RetCode.SUCCESS,CommonConsts.SPACE,result);
		}
		
	}
	
	
	
}
